/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Kanet
 */
public class DataProvider {
    private Connection connection;
    public Connection getConnection(){
        return connection;
    }
    public Connection open(){
        connection=null;
        try{
            Driver driver=new org.gjt.mm.mysql.Driver();
            DriverManager.registerDriver(driver);
            String conString="jdbc:mysql://localhost:3306/chozoi";
            Properties info=new Properties();
            info.setProperty("characterEncoding", "utf-8");
            info.setProperty("user", "root");
            info.setProperty("password", "root");
            connection=DriverManager.getConnection(conString,info);

        }catch(SQLException ex){
            System.out.println(ex.getMessage());
        }
        return connection;
    }
    
    public void close()
    {
        try {
            if(!this.connection.isClosed())
                this.connection.close();
        } catch (SQLException ex) 
        {
            Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public ResultSet executeQuery(String sql) throws SQLException
    {
        ResultSet rs = null;
        try {            
            Statement sm = this.connection.createStatement();
            rs = sm.executeQuery(sql);
        } catch (SQLException ex) {
            Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }       
        return rs;
    }
    public int executeUpdate(String sql){
        int num = -1;
        try {
            Statement sm = this.connection.createStatement();
            num=sm.executeUpdate(sql);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return num;
    }
    
    public CallableStatement prepareCall(String sql){
        CallableStatement statement=null;
        try {
            statement = this.connection.prepareCall(sql);
        } catch (SQLException ex) {
            Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        return statement;
    }
    
    public PreparedStatement prepareStatement(String sql)
    {
        PreparedStatement statement=null;
        try {
            statement = this.connection.prepareStatement(sql);
        } catch (SQLException ex) {
            Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        return statement;
    }
}
